package com.unione.unione_network

import com.chuckerteam.chucker.api.ChuckerInterceptor
import com.unione.unione_base.view.App
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import java.util.concurrent.TimeUnit

class OKHttpWrapper {

    private var builder = OkHttpClient.Builder()

    companion object {

        @Volatile
        private var wrapper: OKHttpWrapper? = null

        fun get(): OKHttpWrapper {
            return wrapper ?: synchronized(this) {
                wrapper ?: OKHttpWrapper().also {
                    wrapper = it
                }
            }
        }
    }

    fun addInterceptor(interceptor: Interceptor) {
        builder.addInterceptor(interceptor)
    }

    fun addNetworkInterceptor(interceptor: Interceptor) {
        builder.addNetworkInterceptor(interceptor)
    }

    fun client(): OkHttpClient {
        builder.connectTimeout(
            UnioneClient.sOkClientConfig.connectionTimeout,
            TimeUnit.MILLISECONDS
        )
        builder.readTimeout(
            UnioneClient.sOkClientConfig.readTimeout,
            TimeUnit.MILLISECONDS
        )
        builder.writeTimeout(
            UnioneClient.sOkClientConfig.writeTimeout,
            TimeUnit.MILLISECONDS
        )
        builder.addInterceptor(CommonInterceptor())
        builder.addInterceptor(HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))
        builder.addInterceptor(createChuckerInterceptor())
        return builder.build()
    }

    private fun createChuckerInterceptor(): ChuckerInterceptor {
        return ChuckerInterceptor.Builder(App.getContext())
            .maxContentLength(250000L)
            .alwaysReadResponseBody(false)
            .redactHeaders(emptySet())
            .build()
    }
}